package apis

import (
	"fmt"
	"github.com/gin-gonic/gin"
	dto "vrcm/src/vrcm/app/admin/service/dto/live"
	service "vrcm/src/vrcm/app/admin/service/live"
	"vrcm/src/vrcm/common/apis"
)

type LiveRecord struct {
	apis.Api
}

// StartLiveRecord 开启直播录制
func (e LiveRecord) StartLiveRecord(c *gin.Context) {
	req := dto.StartRecordReq{}
	s := service.LiveRecord{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			e.Logger.Error("StartLiveRecord dd:", r)
			tx.Rollback()
		}
	}()
	err = s.StartLiveRecord(tx, &req)
	if err != nil {
		e.Error(apis.StartRecordError.Code, err, fmt.Sprintf("开启录制失败，\r\n失败信息 %s", err.Error()))
		return
	}
	tx.Commit()
	e.OK("", "开启录制成功")
}

// StopLiveRecord 停止直播录制Record
func (e LiveRecord) StopLiveRecord(c *gin.Context) {
	req := dto.StopRecordReq{}
	s := service.LiveRecord{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			e.Logger.Error("StartLiveRecord dd:", r)
			tx.Rollback()
		}
	}()
	err = s.StopLiveRecord(&req)
	if err != nil {
		e.Error(apis.StartRecordError.Code, err, fmt.Sprintf("停止录制失败，\r\n失败信息 %s", err.Error()))
		return
	}
	tx.Commit()
	e.OK("", "停止录制成功")
}

// RecordFileCallBack 录制文件回调
func (e LiveRecord) RecordFileCallBack(c *gin.Context) {
	req := dto.RecordFileCallBack{}
	s := service.LiveRecord{}
	err := e.MakeContext(c).
		MakeOrm().
		Bind(&req).
		MakeService(&s.Service).
		Errors
	if err != nil {
		e.Logger.Error(err)
		e.Error(apis.InternalError.Code, err, err.Error())
		return
	}

	e.Logger.Trace("进入直播录制回调")
	err = s.RecordFileCallBack(&req)
	if err != nil {
		e.Error(apis.SyncRecordError.Code, err, fmt.Sprintf("录制回调失败，失败信息 %s", err.Error()))
		return
	}
	e.OK("", "录制回调成功")
}
